type RouteItem = {
    module: string;
    controller: string;
    action: string;
};

class KeRouter {
    private app;
    private fs;

    constructor (app) {
        this.app = app;
        this.fs = require('fs');
    }

    public register(type, rule : string, controller : string)
    {
        this.app.use(async (ctx, next) => {
            if (type !== ctx.request.method.toLowerCase()) {
                return next();
            }
            let m : boolean = false;
            let Controller;
            let item = { module: 'index', controller: 'index', action: 'index' };
            if (ctx.request.url === rule) {
                const ct = controller.split('/');
                switch (ct.length) {
                    case 1:
                        item.controller = item.controller.replace(/^\S/,function(s){return s.toUpperCase();}) + 'Controller';
                        item.action = ct[0];
                        m = true;
                        break;
                    case 2:
                        item.controller = ct[0].replace(/^\S/,function(s){return s.toUpperCase();}) + 'Controller';
                        item.action = ct[1];
                        m = true;
                        break;
                    case 3:
                        item.module = ct[0];
                        item.controller = ct[1].replace(/^\S/,function(s){return s.toUpperCase();}) + 'Controller';
                        item.action = ct[2];
                        m = true;
                        break;
                    default:
                        break;
                }
            }

            try {
                if (m) {
                    Controller = new (require('../../application/' + item.module + '/controller/' + item.controller))();
                    if (Controller[item.action]) {
                        ctx.body = await Controller[item.action](ctx.request);
                    } else {
                        ctx.body = 'Method: ' + item.action;
                    }
                } else {
                    next();
                }
            } catch (e) {
                console.log(e)
                next();
            }
        })
    }

    public get(rule: string, controller: string)
    {
        return this.register('get', rule, controller);
    }

    public post(rule: string, controller: string)
    {
        return this.register('post', rule, controller);
    }

    public put(rule: string, controller: string)
    {
        return this.register('put', rule, controller);
    }

    public delete(rule: string, controller: string)
    {
        return this.register('delete', rule, controller);
    }

}

module.exports = KeRouter;
